package top.chenfu.security.config.security;

import com.alibaba.fastjson.JSON;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringBootConfiguration;
import org.springframework.context.annotation.Bean;
import org.springframework.http.MediaType;
import org.springframework.security.authentication.*;
import org.springframework.security.config.annotation.ObjectPostProcessor;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.web.access.intercept.FilterSecurityInterceptor;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.security.web.authentication.logout.LogoutSuccessHandler;
import top.chenfu.security.service.UserService;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;

/**
 * @Auther chenfu
 * @2019/10/29 13:00
 * @Desc
 */
@SpringBootConfiguration
public class MySecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    private UserService userDetailsService;

    @Autowired
    private AuthenticationAccessDeniedHandler authenticationAccessDeniedHandler;

    @Autowired
    private CustomMetadataSource customMetadataSource;

    @Autowired
    private UrlAccessDecisionManager urlAccessDecisionManager;

    /**
     * 密码加密
     *
     * @return
     */
    @Bean
    public BCryptPasswordEncoder bCryptPasswordEncoder() {
        return new BCryptPasswordEncoder();
    }

    /**
     * 认证
     *
     * @param auth
     * @throws Exception
     */
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(userDetailsService);
    }

    /**
     * 授权
     *
     * @param http
     * @throws Exception
     */
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests()
//                动态权限配置
                .withObjectPostProcessor(new ObjectPostProcessor<FilterSecurityInterceptor>() {
                    @Override
                    public <O extends FilterSecurityInterceptor> O postProcess(O o) {
                        o.setSecurityMetadataSource(customMetadataSource);
                        o.setAccessDecisionManager(urlAccessDecisionManager);
                        return o;
                    }
                })
                .and()
                .formLogin().loginProcessingUrl("/login")
                .usernameParameter("username").passwordParameter("password")
                .successHandler(new AuthenticationSuccessHandler() {
                    @Override
                    public void onAuthenticationSuccess(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Authentication authentication) throws IOException, ServletException {
                        httpServletResponse.setContentType(MediaType.APPLICATION_JSON_UTF8_VALUE);
                        PrintWriter writer = httpServletResponse.getWriter();
                        HashMap<String, Object> result = new HashMap<>();
                        result.put("msg", "登录成功");
                        result.put("code", 200);
                        result.put("data", authentication.getPrincipal());
                        System.out.println(authentication.getAuthorities());
                        System.out.println(authentication.getDetails());
                        System.out.println(authentication.getPrincipal());
                        writer.write(JSON.toJSONString(result));
                        writer.flush();
                        writer.close();
                    }
                }).failureHandler(new AuthenticationFailureHandler() {
            @Override
            public void onAuthenticationFailure(HttpServletRequest httpServletRequest, HttpServletResponse resp, AuthenticationException e) throws IOException, ServletException {
                resp.setContentType(MediaType.APPLICATION_JSON_UTF8_VALUE);
                HashMap<String, Object> result = new HashMap<>();
                if (e instanceof BadCredentialsException ||
                        e instanceof UsernameNotFoundException) {
                    result.put("msg", "账户名或者密码输入错误!");
                } else if (e instanceof LockedException) {
                    result.put("msg", "账户被锁定，请联系管理员!");
                } else if (e instanceof CredentialsExpiredException) {
                    result.put("msg", "密码过期，请联系管理员!");
                } else if (e instanceof AccountExpiredException) {
                    result.put("msg", "账户过期，请联系管理员!");
                } else if (e instanceof DisabledException) {
                    result.put("msg", "账户被禁用，请联系管理员!");
                } else {
                    result.put("msg", "登录失败!");
                }
                resp.setStatus(401);
                PrintWriter out = resp.getWriter();
                out.write(JSON.toJSONString(result));
                out.flush();
                out.close();
            }
        }).permitAll()
                .and()
                .logout().logoutUrl("/logout")
                .logoutSuccessHandler(new LogoutSuccessHandler() {
                    @Override
                    public void onLogoutSuccess(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Authentication authentication) throws IOException, ServletException {
                        httpServletResponse.setContentType(MediaType.APPLICATION_JSON_UTF8_VALUE);
                        HashMap<String, Object> result = new HashMap<>();
                        result.put("msg", "注销成功");
                        PrintWriter writer = httpServletResponse.getWriter();
                        writer.write(JSON.toJSONString(result));
                        writer.flush();
                        writer.close();
                    }
                })
                .permitAll()
                .and().csrf().disable()
                .exceptionHandling().accessDeniedHandler(authenticationAccessDeniedHandler);

        http.addFilterAt(myAuthenticationFilter(), UsernamePasswordAuthenticationFilter.class);
    }

    @Bean
    MyAuthenticationFilter myAuthenticationFilter() throws Exception {
        MyAuthenticationFilter filter = new MyAuthenticationFilter();
        filter.setAuthenticationSuccessHandler(new AuthenticationSuccessHandler() {
            @Override
            public void onAuthenticationSuccess(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Authentication authentication) throws IOException, ServletException {
                httpServletResponse.setContentType(MediaType.APPLICATION_JSON_UTF8_VALUE);
                PrintWriter writer = httpServletResponse.getWriter();
                HashMap<String, Object> result = new HashMap<>();
                result.put("msg", "登录成功");
                result.put("code", 200);
                result.put("data", authentication.getCredentials());
                writer.write(JSON.toJSONString(result));
                writer.flush();
                writer.close();
            }
        });
        filter.setAuthenticationFailureHandler(new AuthenticationFailureHandler() {
            @Override
            public void onAuthenticationFailure(HttpServletRequest httpServletRequest, HttpServletResponse resp, AuthenticationException e) throws IOException, ServletException {
                resp.setStatus(401);
                resp.setContentType(MediaType.APPLICATION_JSON_UTF8_VALUE);
                HashMap<String, Object> result = new HashMap<>();
                result.put("msg", "登录失败");
                PrintWriter writer = resp.getWriter();
                writer.write(JSON.toJSONString(result));
                writer.flush();
                writer.close();
            }
        });
        filter.setAuthenticationManager(authenticationManagerBean());
        return filter;
    }

}
